import Router from'koa-router';
import { signupWx, findByOpenId, findByPhone, updateUser } from '../service/user'
import { jscode2session } from '../service/weixin'
import userAuthed from '../middleware/userAuthed'
import { BASE_URL } from '../config'
import { getWxEncrypted } from '../utils/tools';
import { encode } from '../utils/token';

const router = new Router();
/**
 * 用户登录
 */
router.post('/login', async (ctx) => {
  let { code } = ctx.request.body;
  if (!code) return ctx.error({ message: '请输入完整信息' })
  const { data } = await jscode2session(code).catch((err)=>{
    console.log(err, 'stf err')
  })
  if (data.errmsg) {
    return ctx.error(data)
  }
  let user = await findByOpenId(data.openid)
  if (!user) {
    user = await signupWx({ ...data , roles: 0 })
  }

  ctx.success({
    token: encode({
      time: Date.now(),
      uid: user.roles,
      id: String(user._id),
    }),
    user,
  }, '登录成功')
});


/**
 * 获取用户信息
 */
router.get('/info', userAuthed, async (ctx) => {
  const user = ctx.user
  ctx.success(user)
});

/**
 * 获取微信解密信息
 */
router.post('/getEncrypted', userAuthed, async (ctx) => {
  const { id } = ctx.user;
  const { code, encryptedData, iv } = ctx.request.body;
  const r = await getWxEncrypted(code, encryptedData, iv)
  if (!r.openId) {
    return ctx.error({ message: '解密失败' })
  }
  let user = await updateUser(id, {
    avatar: r.avatarUrl,
    city: r.city,
    country: r.country,
    gender: r.gender,
    language: r.language,
    username: r.nickName,
    province: r.province
  }); // 更新用户信息
  ctx.success(user, '更新成功')
});


/**
 * 更新用户信息
 */
router.post('/update', userAuthed, async (ctx) => {
  const { id } = ctx.user;
  const updateInfo = ctx.request.body;
  if (user) {
    if (updateInfo.phone) {
      updateInfo.phone = String(updateInfo.phone)
      let phoneUser = await findByPhone(updateInfo.phone);
      if (phoneUser) return ctx.error({  message: '该手机号已存在' })
    }
    user = await updateUser(id, updateInfo); // 更新用户信息
    ctx.success(user, '更新成功')
  } else {
    ctx.error({ message: '用户不存在' })
  }
});

export const path = `${BASE_URL}/user`
export default router
